package com.jxc.action.kcgl;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;

import com.jxc.action.BaseAction;
import com.jxc.model.vo.DataGrid;
import com.jxc.model.vo.Json;
import com.jxc.model.vo.SessionInfo;
import com.jxc.model.vo.VBrand;
import com.jxc.model.vo.VDamagelist;
import com.jxc.model.vo.VDamagelistItem;
import com.jxc.model.vo.VGoods;
import com.jxc.model.vo.VRepertory;
import com.jxc.model.vo.VUser;
import com.jxc.service.DamagelistItemServiceI;
import com.jxc.service.DamagelistServiceI;
import com.jxc.service.GoodsServiceI;
import com.jxc.service.RepertoryServiceI;
import com.jxc.service.UserServiceI;
import com.jxc.util.ExceptionUtil;
import com.jxc.util.ResourceUtil;
import com.opensymphony.xwork2.ModelDriven;

@Namespace("/kcgl")
@Action(value = "goodsDamageAction", results = { @Result(name = "goodsDamage", location = "/amountRelate/goodsDamage.jsp") })
public class GoodsDamageAction extends BaseAction implements ModelDriven<VDamagelist> {
	private final static Logger logger = Logger.getLogger(GoodsDamageAction.class);

	private VDamagelist model = new VDamagelist();
	private String items;

	@Autowired
	private DamagelistServiceI damagelistService;
	@Autowired
	private DamagelistItemServiceI damagelistItemService;
	@Autowired
	private UserServiceI userService;
	@Autowired
	private RepertoryServiceI repertoryService;
	@Autowired
	private GoodsServiceI goodsService;

	public String goodsDamage() {
		getSubAuths("KCGL_KCBS");
		return "goodsDamage";
	}

	public String goodsTransferItem() {
		return "goodsTransferItem";
	}

	public void datagrid() throws Exception {
		if (model.getBeginDate() != null) {
			String beginDateStr = new SimpleDateFormat("yyyy-MM-dd").format(model.getBeginDate());
			model.setBeginDate(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(beginDateStr + " 00:00:00"));
		}
		if (model.getEndDate() != null) {
			String endDateStr = new SimpleDateFormat("yyyy-MM-dd").format(model.getEndDate());
			model.setEndDate(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(endDateStr + " 23:59:59"));
		}
		if (model.getRid() != null) {
			this.writeJson(damagelistService.datagrid(model));
		} else {
			SessionInfo sessionInfo = (SessionInfo) ServletActionContext.getRequest().getSession().getAttribute(ResourceUtil.getSessionInfoName());
			VUser vuser = userService.get(sessionInfo.getUserId());
			if (vuser.getReid() != null) {
				model.setRid(vuser.getReid());
				this.writeJson(damagelistService.datagrid(model));
			} else {
				VRepertory vrepertory = new VRepertory();
				vrepertory.setUid(sessionInfo.getUserId());
				List<VRepertory> vrepertories = repertoryService.list(vrepertory);
				if (vrepertories != null && vrepertories.size() > 0) {
					List<VBrand> rows = new ArrayList<VBrand>();
					Long total = 0l;
					for (VRepertory vre : vrepertories) {
						model.setRid(vre.getId());
						DataGrid subDg = damagelistService.datagrid(model);
						rows.addAll(subDg.getRows());
						total += subDg.getTotal();
					}
					DataGrid totalDg = new DataGrid();
					totalDg.setRows(rows);
					totalDg.setTotal(total);
					this.writeJson(totalDg);
				} else {
					DataGrid dg = new DataGrid();
					dg.setTotal(0l);
					dg.setRows(new ArrayList<VBrand>());
					this.writeJson(dg);
				}
			}
		}
	}

	public void noAuth_search() {
		this.writeJson(this.damagelistService.combobox(model));
	}

	/**
	 * 库存调拔单添加
	 */
	public void add() {
		Json j = new Json();
		try {
			model.setIsConfirm(false);
			Long id = damagelistService.save(model);

			Integer totalNum = 0;
			
			String[] args = items.split(",");
			Map<String, VDamagelistItem> itemMap = new HashMap<String, VDamagelistItem>();
			for (int i = 0; i < args.length; i++) {
				String gid = args[i];
				String num = args[++i];
				String total = args[++i];
				
				totalNum += Integer.parseInt(num);

				VDamagelistItem vdli = itemMap.get(gid);
				if (vdli == null) {
					vdli = new VDamagelistItem();
					vdli.setNum(Integer.parseInt(num));
					vdli.setTotal(Double.parseDouble(total));
					vdli.setGid(Long.parseLong(gid));
					vdli.setDlid(id);
					itemMap.put(gid, vdli);
				} else {
					vdli.setNum(vdli.getNum() + Integer.parseInt(num));
					vdli.setTotal(vdli.getTotal() + Double.parseDouble(total));
				}
			}

			Collection<VDamagelistItem> items = itemMap.values();
			for (VDamagelistItem item : items) {
				damagelistItemService.save(item);
			}
			
			VDamagelist param = new VDamagelist();
			param.setId(id);
			List<VDamagelist> list = damagelistService.combobox(param);
			VDamagelist vd = list.get(0);
			vd.setNum(totalNum);
			damagelistService.update(vd);
			
			j.setMsg("添加成功！");
			j.setSuccess(true);
		} catch (Exception e) {
			j.setMsg("添加失败！");
			logger.info(ExceptionUtil.getExceptionMessage(e));
		}
		super.writeJson(j);
	}

	/**
	 * 修改报损单
	 * 
	 */
	public void edit() {
		Json j = new Json();
		try {
			model.setIsConfirm(false);
			Long id = damagelistService.update(model);

			Integer totalNum = 0;
			
			String[] args = items.split(",");
			Map<String, VDamagelistItem> itemMap = new HashMap<String, VDamagelistItem>();
			for (int i = 0; i < args.length; i++) {
				String vId = args[i];
				String gid = args[++i];
				String num = args[++i];
				String total = args[++i];
				
				totalNum+= Integer.parseInt(num);

				VDamagelistItem vdli = itemMap.get(gid);
				if (vdli == null) {
					if (StringUtils.isBlank(vId)) {
						vdli = new VDamagelistItem();
						vdli.setNum(Integer.parseInt(num));
						vdli.setTotal(Double.parseDouble(total));
						vdli.setGid(Long.parseLong(gid));
						vdli.setDlid(id);
					} else {
						VDamagelistItem param = new VDamagelistItem();
						param.setId(Long.parseLong(vId));
						List<VDamagelistItem> vdlis = damagelistItemService.combobox(param);
						vdli = vdlis.get(0);
						vdli.setNum(Integer.parseInt(num));
						vdli.setTotal(Double.parseDouble(total));
						vdli.setGid(Long.parseLong(gid));
					}
					itemMap.put(gid, vdli);
				} else {
					vdli.setNum(vdli.getNum() + Integer.parseInt(num));
					vdli.setTotal(vdli.getTotal() + Double.parseDouble(total));
				}
			}

			Collection<VDamagelistItem> items = itemMap.values();
			for (VDamagelistItem item : items) {
				damagelistItemService.saveOrUpdate(item);
			}
			
			VDamagelist param = new VDamagelist();
			param.setId(id);
			List<VDamagelist> list = damagelistService.combobox(param);
			VDamagelist vd = list.get(0);
			vd.setNum(totalNum);
			damagelistService.update(vd);

			j.setSuccess(true);
			j.setMsg("编辑成功！");
		} catch (Exception e) {
			logger.error(ExceptionUtil.getExceptionMessage(e));
			j.setMsg("编辑失败！");
		}
		super.writeJson(j);
	}

	/**
	 * 删除报损单
	 * 
	 */
	public void delete() {
		Json j = new Json();
		damagelistService.delete(model.getIds());
		j.setSuccess(true);
		j.setMsg("删除成功!");
		super.writeJson(j);
	}

	/**
	 * 确认报损单
	 * 
	 */
	public void confirm() {
		Json j = new Json();
		SessionInfo sessionInfo = (SessionInfo) ServletActionContext.getRequest().getSession().getAttribute(ResourceUtil.getSessionInfoName());
		List<VDamagelist> vdls = damagelistService.combobox(model);
		VDamagelist vdl = vdls.get(0);

		vdl.setCuid(sessionInfo.getUserId());
		vdl.setConfirmDate(new Date());
		vdl.setIsConfirm(true);
		damagelistService.update(vdl);

		VDamagelistItem param = new VDamagelistItem();
		param.setDlid(model.getId());
		List<VDamagelistItem> items = damagelistItemService.combobox(param);
		for (VDamagelistItem item : items) {
			VGoods paramg = new VGoods();
			paramg.setId(item.getGid());
			List<VGoods> vgs = goodsService.combobox(paramg);
			VGoods vg = vgs.get(0);
			vg.setAmount(vg.getAmount() - item.getNum());
			vg.setDamageTotal(vg.getDamageTotal() + item.getNum());
			goodsService.update(vg);
		}
		j.setSuccess(true);
		j.setMsg("确认成功!");
		super.writeJson(j);
	}

	@Override
	public VDamagelist getModel() {
		return model;
	}

	public String getItems() {
		return items;
	}

	public void setItems(String items) {
		this.items = items;
	}

}
